// pages/area/area.js
const utils = require('../../utils/util.js')
const gd = getApp().globalData; //全局变量对象
const getStorage = utils.wxPromisify(wx.getStorage)
const setStorage = utils.wxPromisify(wx.setStorage)

Page({

  /**
   * 页面的初始数据
   */
  data: {
    viewHeight: wx.getSystemInfoSync().screenHeight,
    visible: false,
    pavilion: '',
    searchvisible: true,
    museums: [],
    zindex: -1,
    op: 0,
    isLocation: false, //判断是否是附近博物馆
    visible3: false,    //手动授权提示框
    actions3: [
      {
        name: '确认',
        color: '#2d8cf0',
      }
    ],
  },

  /**
   * 提交展馆编号
   */
  areaSubmit: function(pavilion) {
    if (!pavilion || pavilion == '') {
      this.setData({
        pavilion: ''
      })
      wx.showToast({
        title: '请输入正确的编号',
        icon: 'none',
        duration: 1000
      })
      return
    }
    wx.showLoading({
      title: '加载中',
      mask: true
    })
    const url = gd.domain + gd.museumExcelName
    utils.requestExcelToJson(url)
      .then(res => {
        this.findAndToIndex(res, pavilion)
      }, err => {
        wx.showToast({
          title: '网络请求失败',
          icon: 'none',
          duration: 1000
        })
      })
  },
  //查找并跳转到主页
  findAndToIndex: function(data, pavilion) {
    const area = utils.findEqual(data, 'museum', pavilion);
    if (!area) {
      this.setData({
        pavilion: ''
      })
      wx.showToast({
        title: '请输入正确的编号',
        icon: 'none',
        duration: 1000
      })
      return
    }
    this.setData({
      visible: false
    });

    setStorage({
      key: 'area',
      data: area
    }).then(res => {
      wx.redirectTo({
        url: '/pages/index/index',
      })
    })
  },
  toIndex: function(event) {
    const area = event.currentTarget.dataset.area
    setStorage({
      key: 'area',
      data: area
    }).then(res => {
      wx.redirectTo({
        url: '/pages/index/index',
      })
    })
  },

  /**
   * 生命周期函数--监听页面加载
   * 
   */
  onLoad: function(options) {
    if (options.pavilion){
      this.areaSubmit(options.pavilion)
    }
    //首次检测
    getStorage({
      key: 'area'
    }).then(res => {
      wx.redirectTo({
        url: '/pages/index/index',
      })
    }, err => {
      console.log(err)
    })
    wx.getLocation({
      type: 'wgs84',
      success: function (res) {
      }
    })
  },
  //扫码
  saoma: function() {
    wx.scanCode({
      success: res => {
        this.areaSubmit(res.result)
      }
    })
  },
  //搜索博物馆按钮点击事件
  toSearch: function() {
    const url = gd.domain + gd.museumExcelName
    utils.requestExcelToJson(url)
      .then(res => {
        wx.setStorageSync("museummap", res)
        //获取用户的实时位置,并准备提供附近展馆的信息
        this.getUserLoaction(res)
      }, err => {
        wx.showToast({
          title: '网络请求失败',
          icon: 'none',
          duration: 1000
        })
      })

    this.setData({
      zindex: 999
    })
    let timer = setInterval(() => {
      if (this.data.op >= 1) {
        clearInterval(timer)
      }
      this.setData({
        op: this.data.op + 0.2
      })
    }, 100)
  },
  //隐藏搜索栏
  hideInput: function() {
    this.setData({
      zindex: -1,
      op: 0
    })
  },

  //input输入事件
  forName: function(e) {
    this.setData({
      pavilion: e.detail.value
    })
  },


  //input清除输入
  clearInput: function() {
    this.setData({
      inputVal: ""
    });
  },

  //搜索事件
  searchMuseum: function(e) {
    const that = this
    let value = e.detail.value
    if (value == '') return //|| value.length < 2
    wx.showLoading({
      title: '加载中'
    })

    //获取映射数据
    const museummap = wx.getStorageSync('museummap')
    if (museummap) {
      const museums = utils.findforRegExp(museummap, 'museum_name', value);
      that.setData({
        museums,
        inputVal: e.detail.value,
        isLocation: false
      })
    } else {
      const url = gd.domain + gd.museumExcelName
      utils.requestExcelToJson(url)
        .then(res => {
          //找到匹配的数据
          const museums = utils.findforRegExp(res, 'museum_name', value);
          that.setData({
            museums,
            inputVal: e.detail.value,
            isLocation: false
          })
          //找到对应映射跳转页面
          setStorage({
            key: 'museummap',
            data: res
          })
        }, err => {
          wx.showToast({
            title: '网络请求失败',
            icon: 'none',
            duration: 1000
          })
        })
    }
    const hideNum = setInterval(() => {
      wx.hideLoading()
      clearInterval(hideNum)
    }, 1000)

  },


  //彩蛋输入框 
  //显示弹出框
  handleOpen() {
    this.setData({
      visible: true
    });
  },
  //关闭弹出框
  handleClose() {
    this.setData({
      visible: false,
      pavilion: ''
    });
  },
  //提交
  handleComfirm() {
    // console.log('输入的内容是：' + this.data.pavilion)
    this.areaSubmit(this.data.pavilion)
  },

  //请求获取用户的实时位置,并准备提供附近展馆的信息
  getUserLoaction(museummap) {
    let that = this
    //展馆测试数据
    if (!museummap) {
      museummap = wx.getStorageSync("museummap")
    }
    wx.showToast({
      title: '搜索附近展馆中',
      icon: 'none'
    })
    wx.getSetting({
      success: function (res) {
        var statu = res.authSetting;
        if (!statu['scope.userLocation']) {
          wx.showModal({
            title: '是否授权当前位置',
            content: '需要获取您的地理位置，请确认授权，否则展示附近展馆功能将无法使用',
            success: function (tip) {
              if (tip.confirm) {
                let temp = 0;  //标识是否授权
                wx.openSetting({
                  success: function (data) {
                    wx.getSetting({
                      success(res) {
                        var statu = res.authSetting;
                        console.log("授权： ---------" + statu['scope.userLocation'])
                        if (!statu['scope.userLocation']) {
                          console.log(statu['scope.userLocation'])
                          //用户未授权
                          wx.showToast({
                            title: '授权失败T.T',
                            icon: 'none',
                            duration: 1000
                          })
                        } else {
                          // 授权成功之后，再调用搜索附近展馆
                          that.getUserLocationMuseum(museummap)
                        }
                      }
                    })
                  }
                })

              } else {
                console.log(33333333333)
                wx.showToast({
                  title: '授权失败T.T',
                  icon: 'none',
                  duration: 1000
                })
              }
            }
          })
        } else {
          that.getUserLocationMuseum(museummap)
        }
      },
      fail: function (res) {
        wx.showToast({
          title: '调用授权窗口失败',
          icon: 'success',
          duration: 1000
        })
      }
    })
    
  },
  getUserLocationMuseum(museummap){
    let that = this
    wx.getLocation({
      type: 'wgs84', //gps坐标
      success(res) {
        let {
          latitude,
          longitude
        } = res;
        //附近的展馆的临时数组
        let tempMuseum = museummap.filter(item => {
          return latitude - 0.22 <= latitude && item.latitude <= latitude + 0.22 &&
            longitude - 0.18 <= item.longitude && item.longitude <= longitude + 0.18
        })
        //将符合的展馆数组放入data
        that.setData({
          museums: tempMuseum,
          isLocation: true,
          inputVal: ''
        })

        wx.showToast({
          title: '成功搜索展馆',
          icon: 'none'
        })
      },
      fail(err) {
       that.setData({
         visible3:true
       })
      }
    })
  },
  //handleClick3  提醒用户手动打开定位弹出框的隐藏事件
  handleClick3() {
    this.setData({
      visible3: false
    })
  }

})